//
//  PKRadioMainViewController.m
//  PianKe
//
//  Created by lanou on 15/12/21.
//  Copyright © 2015年 KFC. All rights reserved.
//

#import "PKRadioMainViewController.h"
#import "PKRadioTableViewCell.h"
#import "PKRadioModel.h"
#import "PKRadioHeadView.h"
#import "PKRadioDetailViewController.h"

@interface PKRadioMainViewController ()<UITableViewDataSource,UITableViewDelegate, UIScrollViewDelegate>


// 展示的 表示图
@property (strong, nonatomic) UITableView *tableView;
// 提供tableView数据的数组
@property (strong, nonatomic) NSMutableArray *dataArray;
// 提供表头展示数据的数组
@property (strong, nonatomic) NSMutableArray *hotListDataArray;
@property (strong, nonatomic) NSMutableArray *carouselDataArray;

// 表头view
@property (strong, nonatomic) PKRadioHeadView *headView;

// 修改请求的厨师位置
@property (assign, nonatomic) NSInteger requestStart;



@end

@implementation PKRadioMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    _requestStart = 0;
    
    
    self.view.backgroundColor = [UIColor orangeColor];
    self.dataArray = [NSMutableArray array];
    self.hotListDataArray = [NSMutableArray array];
    self.carouselDataArray = [NSMutableArray array];
   
    [self addTableView];
    
#pragma mark ----- 设置loading
    [self p_setupProgressHud];
    
 
    [self setUpData];
    
  
#pragma mark ----- 上拉加载
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
       
        // 上啦加载进行调用这个方法
         _requestStart = _requestStart + 9;
        
        [self addListData];
        
    }];
    
    

#pragma mark ----- 下拉刷新
     _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
         
         _requestStart = 0;
         [self setUpData];
         
     }];
    
    
    
    
}


// 上啦加载数据
- (void)addListData
{
    // 创建一个字典
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"63A94D37-33F9-40FF-9EBB-481182338873";
    parDic[@"version"] = @"3.0.2";
    parDic[@"limit"] = @"9";
    parDic[@"start"] = [NSString stringWithFormat:@"%ld",_requestStart];
    
    [PKRequestManager requestWithUrlString:@"http://api2.pianke.me/ting/radio_list" parDic:parDic Method:POST finish:^(NSData *data) {
        
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        
        
#pragma mark ---- 加载取cell上展示的数据
        NSDictionary *dataDic = dic[@"data"];
        NSArray *array = dataDic[@"list"];
        for (NSDictionary *oneDic in array) {
            
            PKRadioModel *model = [[PKRadioModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [self.dataArray addObject:model];
            
        }
    
#pragma mark ---- 结束加载
        [_tableView.mj_footer endRefreshing];
        [_tableView reloadData];
        
        
    } error:^(NSError *error) {
        
        NSLog(@"%@",error);
        
    }];
    
}







// 处理数据
- (void)setUpData
{
    
    
    // 创建一个字典
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"auth"] = @"XMdnEiW0m3qxDCMVzGMTikDJxQ8aoNbKF8W1rUDRicWP23tB NQhpd6fw";
    parDic[@"client"] = @"1";
    parDic[@"deviceid"] = @"63A94D37-33F9-40FF-9EBB-481182338873";
    parDic[@"version"] = @"3.0.2";
    [PKRequestManager requestWithUrlString:@"http://api2.pianke.me/ting/radio" parDic:parDic Method:POST finish:^(NSData *data) {

        // json解析
        NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
#pragma mark ---- 取cell上展示的数据
        NSDictionary *dataDic = dic[@"data"];
        NSArray *array = dataDic[@"alllist"];
//        
        // 每次都清零,防止下拉刷新的的时候,数据重复
        [_dataArray removeAllObjects];

        for (NSDictionary *oneDic in array) {
           
            PKRadioModel *model = [[PKRadioModel alloc] init];
            [model setValuesForKeysWithDictionary:oneDic];
            [self.dataArray addObject:model];
            
        }
 

        
#pragma mark ---- 取hotList数据
        NSArray *array2 = dataDic[@"hotlist"];
        for (NSDictionary *twoDic in array2) {
            
            PKRadioModel *model = [[PKRadioModel alloc] init];
            [model setValuesForKeysWithDictionary:twoDic];
            [self.hotListDataArray addObject:model];
            
        }
#pragma mark ---- 取轮播的数据       
        NSArray *array3 = dataDic[@"carousel"];
        for (NSDictionary *threeDic in array3) {
            
            PKRadioModel *model = [[PKRadioModel alloc] init];
            [model setValuesForKeysWithDictionary:threeDic];
            [self.carouselDataArray addObject:model];
            
        }
   
        
#pragma mark ---- 结束下拉刷新
        [_tableView.mj_header endRefreshing];

        // 刷新
        [self.tableView reloadData];
        
#pragma mark ----- 关闭loading
      //  self.hud.hidden = YES;
        [self.hud hide:YES];
        
    } error:^(NSError *error) {
        
        NSLog(@"%@",error);
        
    }];
    
    
}


- (void)addTableView
{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:(UITableViewStylePlain)];
    self.tableView.rowHeight = 100;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    // 添加表头
    self.headView = [[PKRadioHeadView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 300)];
    self.tableView.tableHeaderView = self.headView;
    
    // 设置轮播的代理
    self.headView.scrollerV.delegate = self;

    // 加个定时器
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    
    
    // 给热门按钮添加响应
    self.headView.buttonLeft.tag = 100;
    self.headView.buttonMiddle.tag = 101;
    self.headView.buttonRight.tag = 102;
    [self.headView.buttonLeft addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headView.buttonMiddle addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headView.buttonRight addTarget:self action:@selector(buttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    // 给轮播添加响应 (1和3是一样的)
    self.headView.button.tag = 1003;
    self.headView.button1.tag = 1001;
    self.headView.button2.tag = 1002;
    self.headView.button3.tag = 1003;
    
    [self.headView.button addTarget:self action:@selector(scrollAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headView.button1 addTarget:self action:@selector(scrollAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headView.button2 addTarget:self action:@selector(scrollAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.headView.button3 addTarget:self action:@selector(scrollAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    
    
    [self.view addSubview:self.tableView];

}

// 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"RadioCell";
    PKRadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        
        cell = [[PKRadioTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    // 展示数据
    
    PKRadioModel *model = self.dataArray[indexPath.row];
    cell.model = model;
    
    if (indexPath.row == 0) {
        
        self.headView.hotListArray = self.hotListDataArray;
        self.headView.carouselArray = self.carouselDataArray;
        
    }
    
    
    return cell;
}


#pragma mark  ----- 跳转
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    PKRadioDetailViewController *detailVC = [[PKRadioDetailViewController alloc] init];
    
    PKRadioModel *model = self.dataArray[indexPath.row];
    // 传递id
    detailVC.radioid = model.radioid;
   
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)buttonClick:(UIButton *)button
{
    PKRadioDetailViewController *detailVC = [[PKRadioDetailViewController alloc] init];
    PKRadioModel *radioModel = self.hotListDataArray[button.tag - 100];
    // 传递id
    detailVC.radioid = radioModel.radioid;
    
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)scrollAction:(UIButton *)button
{
    
    PKRadioDetailViewController *detailVC = [[PKRadioDetailViewController alloc] init];
    NSString *radioID = nil;

    PKRadioModel *radioModel = self.carouselDataArray[button.tag - 1001];
    radioID = [radioModel.url substringFromIndex:12];

    // 传递id号
    detailVC.radioid = radioID;
    
    [self.navigationController pushViewController:detailVC animated:YES];

}









#pragma mark ---- 轮播
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 一滑动就触发
    
    // 取出scrollView的宽度
    CGFloat width = scrollView.frame.size.width;
    // 取出偏移量
    CGFloat x = scrollView.contentOffset.x;
   // NSLog(@"lalala%f",x);
    
    if (x < 0) {
        // 说明滑动到第一张: 假图
        // 需要偏移到最后一张图
        [scrollView setContentOffset:CGPointMake(width * 3, 0) animated:NO];
    }
    
    if (x > width * 3) {
        // 说明滑动到最后一个图 : 真图
        // 需要便宜到第一张: 假图
        [scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    }
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // 对pageControl进行修改
    CGFloat x = scrollView.contentOffset.x;
    CGFloat width = scrollView.frame.size.width;
    
    NSInteger page = x / width;
    
    if (page == 0) {
        self.headView.pageControl.currentPage = 3;
    } else {
        
        self.headView.pageControl.currentPage = page - 1;
    }
    
}

// 定时器方法
- (void)timer:(NSTimer *)timer
{
    // 如果需要重新定位 先定位再动画， 否则直接动画
    CGFloat x = self.headView.scrollerV.contentOffset.x;
    CGFloat width = self.headView.scrollerV.width;
    
    if (width + x >= self.headView.scrollerV.contentSize.width) {
        
        // 先定位
        [self.headView.scrollerV  setContentOffset:CGPointMake(0, 0) animated:NO];
        // 再动画
        [self.headView.scrollerV setContentOffset:CGPointMake(width, 0) animated:YES];
   
    } else {
        [self.headView.scrollerV setContentOffset:CGPointMake(x + width, 0) animated:YES];
    }
    
    // 把pageControl写在动画里就行了
    
}

// 把pageControl写在动画里就行了
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    CGFloat x = self.headView.scrollerV.contentOffset.x;
    CGFloat width = self.headView.scrollerV.width;
    NSInteger page = x / width;
    
    if (page == 0) {
        
        self.headView.pageControl.currentPage = 3;
    } else {
        
        self.headView.pageControl.currentPage = page - 1;
    }
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
